// pages/forum/MyLike/MyLike.js
var currentAccountId
var currentAccountLiked = []
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("接受到的id、",options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let DB = wx.cloud.database()
      currentAccountId = app.globalData.currentAccountId
      DB.collection("User").get().then(res3 => {
        console.log(currentAccountId)//当前用户id
        console.log(res3.data)//用户数据
        for (var i = 0; i < res3.data.length; i++) {
          if (currentAccountId === res3.data[i]._id) {
            currentAccountLiked = res3.data[i].likequestions
            DB.collection("list").get().then(res4 => {
              var questions = []
              for (var j = 0; j < res4.data.length; j++) {
                for (var k = 0; k < currentAccountLiked.length; k++) {
                  if (res4.data[j]._id === currentAccountLiked[k]) {
                    res4.data[j].liked = true
                    questions[questions.length] = res4.data[j]
                  }
                }
              }
              this.setData({ questions: questions })
            })
            break
          }
        }
      })
    
    // console.log(array)
  },
  onPostTap:function(event){
    var id=event.currentTarget.dataset.detailid;
    var questions=this.data.questions
    console.log("当前登录用户的id",currentAccountId)
    console.log("当前点击事件的id",id)
    console.log("当前收藏的问题",questions)
    console.log("当前用户喜欢的问题",currentAccountLiked)
      var index
    for(var i=0;i<questions.length;i++)
    {
      if(questions[i]._id===id)
      {
        index=i
        break
      }
    }
    questions.splice(index,1)
    this.setData({
      questions:questions
    })
    var index2
          for(var i=0;i<currentAccountLiked.length;i++){
        if(currentAccountLiked[i]===id){
          index2=i
          break
        }
      }
    console.log("取消收藏问题的位置",index2)
    currentAccountLiked.splice(index2,1)
    console.log("删除后的问题",currentAccountLiked)
    let db=wx.cloud.database().collection("User").doc(currentAccountId).update({
      data:{
        likequestions:currentAccountLiked
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.setStorageSync('aShow', true)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})